package net.lab1024.sa.admin.module.basedata.customer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.lab1024.sa.admin.module.basedata.customer.domain.entity.CustomerBank;
import net.lab1024.sa.admin.module.basedata.customer.mapper.CustomerBankMapper;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CustomerBankService {

    @Autowired
    private CustomerBankMapper customerBankMapper;

    /**
     * 根据客户编号查询客户银行信息
     *
     * @param customerCode
     * @return
     */
    public List<CustomerBank> getCustomerBankByCustomerCode(String customerCode) {
        if (customerCode == null) {
            throw new BusinessException("查询客户银行信息,客户编号不能为空");
        }
        LambdaQueryWrapper<CustomerBank> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerBank::getCustomerCode, customerCode);
        List<CustomerBank> customerBanks = customerBankMapper.selectList(wrapper);
        return customerBanks;
    }
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateCustomerBank(List<CustomerBank> customerBankList) {
        if (CollectionUtils.isEmpty(customerBankList)) {
            throw new BusinessException("客户银行信息不能为空");
        }
        if (customerBankList.get(0).getCustomerCode() == null) {
            throw new BusinessException("客户编号不能为空");
        }
        List<CustomerBank> customerBankByCustomerCode = getCustomerBankByCustomerCode(customerBankList.get(0).getCustomerCode());
        if (CollectionUtils.isNotEmpty(customerBankByCustomerCode)) {
            // 删除所有数据
            customerBankMapper.deleteByCustomerCode(customerBankList.get(0).getCustomerCode());
        }

        for (CustomerBank customerBank : customerBankList) {
            customerBank.setCustomerCode(customerBankList.get(0).getCustomerCode());
            customerBank.setVersion(customerBank.getVersion() + 1);
            customerBankMapper.insert(customerBank);
            
        }
    }
}